<?php

class Backend_Model_DbTable_Admin extends Zend_Db_Table_Abstract
{

    protected $_name = 'admin';

    public function getAllAdmins($limit = null){
        if(is_null($limit)) return $this->fetchAll("role_id = 2", "full_name");
        else return $this->fetchAll ("role_id = 2", "full_name", $limit[1], $limit[0]);
    }

    public function getAllSales($limit = null){
        $query = $this->select();
        $query->from(array('a1'=>'admin'));
        $query->joinLeft(array('a2'=>'admin'),'a1.supervisor_id = a2.admin_id',array('s_name'=>'a2.full_name'));
        $query->where("a1.role_id = 3");
        if($limit) $query->limit($limit[1], $limit[0]);
        $query->setIntegrityCheck(false);

        return $this->fetchAll($query);

        //if(is_null($limit)) return $this->fetchAll("role_id = 3", "full_name");
        //else return $this->fetchAll ("role_id = 3", "full_name", $limit[1], $limit[0]);
    }

    public function getAdminById($id){
        return $this->fetchRow("admin_id = $id");
    }

    public function getAdminByEmail($email){
        return $this->fetchRow("email = '$email'");
    }

    public function insertAdmin($data){
        $new_data = array(
            'full_name' => $data['full_name'],
            'email' => $data['email'],
            'password' => sha1($data['password']),
            'role_id' => $data['role_id'],
            'contact' => $data['contact'],
            'supervisor_id' => $data['supervisor_id']
        );
        $this->insert($new_data);
    }

    public function updateAdmin($id, $data){
        $new_data = array(
            'full_name' => $data['full_name'],
            'email' => $data['email'],
            'role_id' => $data['role_id'],
            'contact' => $data['contact']
        );
        $this->update($new_data, "admin_id = $id");
    }

    public function deleteAdmin($id){
        //move to admin_deleted
        $admin = $this->fetchRow("admin_id = $id")->toArray();
        $db = $this->getAdapter();
        $db->insert("admin_deleted", array(
            'admin_id' => $admin['admin_id'],
            'full_name' => $admin['full_name'],
            'email' => $admin['email'],
            'password' => $admin['password'],
            'role_id' => $admin['role_id'],
            'contact' => $admin['contact'],
            'supervisor_id' => $admin['supervisor_id']
        ));

        //delete from original table
        $this->delete("admin_id = $id");
    }
}

